package lei.j_java泛型_匿名内部类_反射.反射;

/**
 * @className: ReflectionExample
 * @author: xl
 * @date: 2025/3/1 16:15
 * @Version: 1.0
 * @description:
 */

import java.lang.reflect.Field;

class Student {
    private String name;
    public int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{name='" + name + "', age=" + age + "}";
    }
}

public class Reflection访问字段Example {
    public static void main(String[] args) throws Exception {
        // 获取 Class 对象
        Class<?> clazz = Class.forName("lei.j_java泛型_匿名内部类_反射.反射.Student");

        // 创建对象
        Object student = clazz.getConstructor(String.class, int.class).newInstance("Alice", 20);

        System.out.println( student.getClass());

        // 访问公共字段
        Field ageField = clazz.getField("age");


        int age = (int) ageField.get(student);// 获取字段的值
        System.out.println("Age: " + age); // 输出: Age: 20

        // 修改公共字段
        ageField.set(student, 25);// 修改字段的值
        System.out.println(student); // 输出: Student{name='Alice', age=25}

        // 访问私有字段
        Field nameField = clazz.getDeclaredField("name");
        nameField.setAccessible(true); // 设置私有字段可访问
        String name = (String) nameField.get(student);
        System.out.println("Name: " + name); // 输出: Name: Alice

        // 修改私有字段
        nameField.set(student, "Bob");
        System.out.println(student); // 输出: Student{name='Bob', age=25}
    }
}
